﻿//Copyright 2010 http://tv4home.codeplex.com
//This file is part of TV4Home.Client.TVViewer.
//TV4Home.Client.TVViewer is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
//TV4Home.Client.TVViewer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//You should have received a copy of the GNU Lesser General Public License along with TV4Home.Client.TVViewer. If not, see http://www.gnu.org/licenses/.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TV4Home.Server.TVEInteractionLibrary.Interfaces;
using System.ServiceModel;
using System.Windows.Threading;
using System.Threading;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.ComponentModel;


namespace TV4Home.Client.Desktop.TVViewer.Pages
{
    /// <summary>
    /// Interaktionslogik für TVViewer.xaml
    /// </summary>
    public partial class TVViewer : Page
    {
        #region Attribute

        ITVEInteraction tvWebClient = null;
        List<WebChannelGroup> _channelGroups;
        List<WebSchedule> _schedules = null;
        List<WebChannelBasic> _channels = null;
        Controls.MediaPlayer MediaPlayer;
        string UserNameStream1;
        string UserNameStream2;

        #endregion


        public TVViewer(Controls.MediaPlayer player)
        {
            InitializeComponent();
            MediaPlayer = player;
         
            UserNameStream1 = Environment.UserName + "Stream1";
            UserNameStream2 = Environment.UserName + "Stream2";
        }





        #region UserControls
        //Event to fill the usercontrol on startup
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            //servername is needed to get information
            if (Properties.Settings.Default.ServerName != "")
            {
                FillPage();
            }
        }
        //connect to tvserver and start filling the usercontrol
        public void FillPage()
        {

            try
            {
                if (Properties.Settings.Default.IsIntranet)
                {
                    ConnectToService();
                }
                else // Internet
                {
                    //Set Endpoint


                }
                //Get all Groups + Schedules

                if (tvWebClient == null)
                {
                    ConnectToService();
                }
                _channelGroups = tvWebClient.GetGroups();
                _schedules = tvWebClient.GetSchedules();



                try
                {

                    _channels = tvWebClient.GetChannelsBasic(Properties.Settings.Default.DefaultGroup);

                    if (_channels != null)
                    {
                        FillTreeView();
                    }
                    else
                    {
                        MessageBox.Show("Keine Channels empfangen");
                    }


                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error loading EPG form, please check your WebServices connection" + ex.Message);
                }
            }
            catch (System.ServiceModel.EndpointNotFoundException ex)
            {
                MessageBox.Show("Exception in FillUserControl" + ex.Message);
            }
        }
        public void FillTreeView()
        {
            trvTVChEpg.Items.Clear();
            if (_channels != null)
            {

                foreach (WebChannelBasic item in _channels)
                {

                    TreeViewItem tvItem = new TreeViewItem();
                    tvItem.Header = item.DisplayName;
                    tvItem.Tag = item;
                    //Add EPG foreach Channel
                    try
                    {
                        if (tvWebClient == null)
                        {
                            ConnectToService();
                        }
                        List<WebProgramBasic> _programs = tvWebClient.GetProgramsBasicForChannel(item.IdChannel, DateTime.Now.AddHours(-2), DateTime.Now.AddHours(10));
                        int j = 0;
                        if (_programs != null)
                        {
                            foreach (WebProgramBasic program in _programs)
                            {

                                if (j >= 4)
                                {
                                    break;
                                }
                                if (DateTime.Now > program.StartTime && DateTime.Now < program.EndTime)
                                {
                                    j++;
                                    MenuItem cmItem = new MenuItem();
                                    TreeViewItem childItem = new TreeViewItem();
                                    ContextMenu cMenu = new System.Windows.Controls.ContextMenu();
                                    childItem.Background = new SolidColorBrush(Colors.Beige);



                                    if (program.IsScheduled)
                                    {
                                        childItem.Background = new SolidColorBrush(Colors.Red);
                                        cmItem.Header = "Stop Record";
                                        cmItem.Click += new RoutedEventHandler(MenuItemStopRecord_Click);
                                        cMenu.Items.Add(cmItem);
                                    }
                                    else
                                    {
                                        cmItem.Header = "Record Program";
                                        cmItem.Click += new RoutedEventHandler(MenuItemRecordProgram_Click);
                                        cMenu.Items.Add(cmItem);
                                    }



                                    childItem.ContextMenu = cMenu;
                                    childItem.Tag = program;
                                    childItem.Header = String.Format("{0} {1}", "Jetzt:", program.Title);
                                    tvItem.Items.Add(childItem);



                                }

                                if (DateTime.Now < program.StartTime && program.StartTime.Date == DateTime.Today && program.StartTime <= DateTime.Now.AddHours(4))
                                {

                                    j++;
                                    MenuItem cmItem = new MenuItem();
                                    TreeViewItem childItem = new TreeViewItem();
                                    ContextMenu cMenu = new System.Windows.Controls.ContextMenu();



                                    if (program.IsScheduled)
                                    {
                                        childItem.Background = new SolidColorBrush(Colors.Red);
                                        cmItem.Header = "Stop Record";
                                        cmItem.Click += new RoutedEventHandler(MenuItemStopRecord_Click);
                                        cMenu.Items.Add(cmItem);
                                    }
                                    else
                                    {
                                        cmItem.Header = "Record Program";
                                        cmItem.Click += new RoutedEventHandler(MenuItemRecordProgram_Click);
                                        cMenu.Items.Add(cmItem);
                                    }


                                    childItem.ContextMenu = cMenu;
                                    childItem.Tag = program;
                                    childItem.Header = String.Format("{0}{1} {2}", program.StartTime.TimeOfDay, ":", program.Title);
                                    tvItem.Items.Add(childItem);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error in filling treeview" + ex.StackTrace.ToString());
                    }

                    trvTVChEpg.Items.Add(tvItem);
                }
            }
        }


        //stops tv server to timeshift, if channel was watched
        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            StopTimeshifting();
        }



        #endregion
     
        #region TreeViewEvents
        private void trvTVChEpg_Selected(object sender, RoutedEventArgs e)
        {
            //check whether selected item is a treeviewitem
            if (e.OriginalSource is TreeViewItem)
            {
                //check type of item(whether its a child or not)
                if (((TreeViewItem)e.OriginalSource).Tag is WebChannelBasic)
                {
                    //if is no child -> it's a channel so start playing the channel
                    try
                    {
                        WebChannelBasic channel = (WebChannelBasic)((TreeViewItem)e.OriginalSource).Tag;
                        PlayChannel(channel);

                    }

                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                if (((TreeViewItem)e.OriginalSource).Tag is WebProgramBasic)
                {
                    //if it's a child change all descriptive controls
                    try
                    {

                        WebProgramBasic program = (WebProgramBasic)((TreeViewItem)e.OriginalSource).Tag;
                        MediaPlayer.AddDescriptions(program.Title, program.Description);
                    

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }
        #region contextmenuitems
        void MenuItemRecordProgram_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem)
            {
                MenuItem contextMenuItem = (MenuItem)sender;

                if (contextMenuItem.Parent is ContextMenu)
                {
                    ContextMenu contextMenu = (ContextMenu)contextMenuItem.Parent;

                    if (contextMenu.PlacementTarget is TreeViewItem)
                    {
                        TreeViewItem originatingTreeViewItem = (TreeViewItem)contextMenu.PlacementTarget;

                        if (originatingTreeViewItem.Tag is WebProgramBasic)
                        {
                            WebProgramBasic program = (WebProgramBasic)originatingTreeViewItem.Tag;



                            try
                            {
                                tvWebClient.AddScheduleDetailed(program.IdChannel, program.Title, program.StartTime, program.EndTime, 0, Properties.Settings.Default.TimeBeforeSchedule, Properties.Settings.Default.TimeAfterSchedule, "", 0);

                                MenuItem cmItem = new MenuItem();
                                cmItem.Header = "Stop Record";
                                cmItem.Click += new RoutedEventHandler(MenuItemStopRecord_Click);

                                originatingTreeViewItem.ContextMenu.Items[0] = cmItem;
                                originatingTreeViewItem.Background = new SolidColorBrush(Colors.Red);



                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Error while adding schedule, please check your WebServices connection" + ex.Message);
                            }

                        }
                    }
                }
            }
        }

        void MenuItemStopRecord_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem)
            {
                MenuItem contextMenuItem = (MenuItem)sender;

                if (contextMenuItem.Parent is ContextMenu)
                {
                    ContextMenu contextMenu = (ContextMenu)contextMenuItem.Parent;

                    if (contextMenu.PlacementTarget is TreeViewItem)
                    {
                        TreeViewItem originatingTreeViewItem = (TreeViewItem)contextMenu.PlacementTarget;

                        if (originatingTreeViewItem.Tag is WebProgramBasic)
                        {
                            WebProgramBasic program = (WebProgramBasic)originatingTreeViewItem.Tag;

                            _schedules = tvWebClient.GetSchedules();

                            foreach (WebSchedule schedule in _schedules)
                            {
                                if (schedule.IdChannel == program.IdChannel && schedule.StartTime == program.StartTime.AddMinutes(-Properties.Settings.Default.TimeBeforeSchedule))
                                {
                                    try
                                    {
                                        tvWebClient.CancelSchedule(program.IdProgram);

                                        MenuItem cmItem = new MenuItem();
                                        cmItem.Header = "Record Program";
                                        cmItem.Click += new RoutedEventHandler(MenuItemRecordProgram_Click);

                                        originatingTreeViewItem.ContextMenu.Items[0] = cmItem;
                                        originatingTreeViewItem.Background = new SolidColorBrush(Colors.White);


                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show("Error while deleting schedule, please check your WebServices connection" + ex.Message);
                                    }

                                }
                            }
                        }
                    }
                }
            }
        }
        #endregion
        #endregion

        #region BasicMethods




        private void PlayChannel(WebChannelBasic channel)
        {
            try
            {

                tvWebClient.CancelCurrentTimeShifting(UserNameStream1);
                string save = tvWebClient.SwitchTVServerToChannelAndGetStreamingUrl(UserNameStream1, channel.IdChannel);
                save = save.Replace(":554", "");
               MediaPlayer.Play(save);
                WebProgramBasic program = tvWebClient.GetCurrentProgramOnChannel(channel.IdChannel);

                string title = "";
                string description = "";
                if (program != null)
                {
                    title = program.Title;
                    description = program.Description;
                }
                MediaPlayer.AddDescriptions(title, description);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        public void StopTimeshifting()
        {
            try
            {
                MediaPlayer.Stop();
                tvWebClient.CancelCurrentTimeShifting(UserNameStream1);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void ConnectToService()
        {
            //Connects to the tv4home webservice by netpipe
            try
            {
                if (Properties.Settings.Default.IsIntranet)
                {
                    try
                    {
                        tvWebClient = ChannelFactory<ITVEInteraction>.CreateChannel(new BasicHttpBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress(String.Format(Properties.Settings.Default.IntranetUrl, Properties.Settings.Default.ServerName)));
                    }
                    catch (CommunicationException ex)
                    {
                        tvWebClient = ChannelFactory<ITVEInteraction>.CreateChannel(new BasicHttpBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress(String.Format(Properties.Settings.Default.IntranetUrl, Properties.Settings.Default.ServerName)));

                    }
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                //if connection is not possible ask whether it retry or not
                string sMessageBoxText = "Verbindung konnte nicht hergestellt werden. Erneut versuchen?";
                string sCaption = "TVViewer";

                MessageBoxButton btnMessageBox = MessageBoxButton.YesNo;
                MessageBoxImage icnMessageBox = MessageBoxImage.Warning;

                MessageBoxResult rsltMessageBox = MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);


                // Process message box results

                switch (rsltMessageBox)
                {

                    case MessageBoxResult.Yes:
                        ConnectToService();

                        break;
                    case MessageBoxResult.No:

                        break;
                }
            }

        }
        #endregion

        private void Page_MouseMove(object sender, MouseEventArgs e)
        {
            MediaPlayer.MouseMoved();
        }


    }
}
